package com.csipsimple.phone;

// import com.csipsimple.utils.Log;

import android.app.IntentService;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.provider.CallLog;
import android.telephony.TelephonyManager;
/**
*
* Intent service  that get calls when the phone rings
*
* credit goes to the following open source projects 
* 
* teddsdroidtools - http://code.google.com/p/teddsdroidtools/
* MyLock - http://code.google.com/p/mylockforandroid/
* auto-answer - http://code.google.com/p/auto-answer/		
* 
*
*
*/
public class CallAnswerIntentService extends IntentService {

	private static final long STARTUP_DELAY = 500L;
	static String THIS_FILE = "CallAnswerIntentService";

	

	
	
	public CallAnswerIntentService() {
		super("CallAnswerIntentService");
	}

	SharedPreferences p;
	SharedPreferences.Editor e;
	
	@Override
	protected void onHandleIntent(Intent intent) {
		Context context = getBaseContext();
		p = context.getSharedPreferences(THIS_FILE, MODE_PRIVATE);
		e = p.edit();
		String action = intent.getStringExtra("actionstring");
//		Logge("intentreceived: "+action);
		if (action.equals(PhoneCallReceiver.SIP_ACTIVE)){
//			Logge("handle SIP ACTIVE");
			if (p.getBoolean("gsmTrigger", false))
			{activateSip(context);}
			else 
			{e.putBoolean("sipTrigger",true);}
//			Logge("handled SIP ACTIVE");

		}
		else if (action.equals(PhoneCallReceiver.SIP_DEACTIVE)){
//			Logge("handle SIP DEACTIVE");
			e.putBoolean("sipTrigger", false);
//			Logge("handled SIP DEACTIVE");
		} else if (action.equals(PhoneCallReceiver.SIP_NUMBER)){
			String sipNumber=intent.getStringExtra("sipnumber");
			e.putString("sipnumber", sipNumber);
//			Logge("handle SIP NUMBER "+sipNumber);
		}
		else
		{	

		/* examine the state of the phone that caused this receiver to fire off */
			String phone_state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
//			Logge("Phonestate "+phone_state);

			if (phone_state.equals(TelephonyManager.EXTRA_STATE_RINGING)) 
			{	
				String number = intent.getStringExtra("number");
				if (number.indexOf("<sip:")<0){
//					Logge("Handle Ringing "+number);
					e.putLong("callstart", System.currentTimeMillis());	
					e.putString("number", number);
					if (p.getBoolean("sipTrigger", false))
					{activateSip(context);}
					else 
					{e.putBoolean("gsmTrigger",true);}
//					Logge("Handled Ringing "+number);
				};
			}
			else if (p.getBoolean("waitPhoneIdle", false)&&phone_state.equals(TelephonyManager.EXTRA_STATE_IDLE))
			{
				TelephonyManager t = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
				if (t.getCallState() ==(TelephonyManager.CALL_STATE_IDLE)){
//					("Handle Idle");
					e.putBoolean("waitPhoneIdle",false);
					 try 
						{
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					
					changeLog(context);
				}
			}
				
			
			}
		e.commit();
		return;
		
	}

	 private void activateSip(Context c){	
		// pause
		 e.putBoolean("gsmTrigger",false);
		 e.putBoolean("sipTrigger",false);
		 e.putBoolean("waitPhoneIdle",true);
		 
		
//		Logge("ActivateSIp");
		
		 try 
		{
			Thread.sleep(STARTUP_DELAY);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		// make sure the phone is ringing...
		TelephonyManager t = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
		if (t.getCallState() != TelephonyManager.CALL_STATE_RINGING)
		return;

		// (re)start the CallAnswerActivity
		Intent i = new Intent();
		i.setClassName("com.urnum","com.csipsimple.ui.InCallActivity2");
		
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		c.startActivity(i);
		
		
		return;
		
		
	}

		private void changeLog(Context context) {
			ContentResolver contentResolver = context.getContentResolver();
			Cursor c=contentResolver.query(CallLog.Calls.CONTENT_URI,
					null,
					CallLog.Calls.NUMBER+"=? AND ("+CallLog.Calls.TYPE+"=? OR "+CallLog.Calls.TYPE+"=? )",
					new String[] {p.getString("number",null), String.valueOf(CallLog.Calls.INCOMING_TYPE), String.valueOf(CallLog.Calls.MISSED_TYPE)},
					CallLog.Calls.DATE+" DESC");
			    
		        
		    ContentValues read_cv = null;
		    if (c!=null) {
		        if (c.moveToFirst()){
		        	read_cv = new ContentValues();
		        	DatabaseUtils.cursorRowToContentValues(c, read_cv);
		        	Long callStart = p.getLong("callstart", 0);
//		        	Log.v(THIS_FILE, "Callstart: "+callStart+ " System:"+(callStart-read_cv.getAsLong(CallLog.Calls.DATE)));
		        	if  (read_cv.getAsLong(CallLog.Calls.DATE)>(callStart-100000)) {
		        		contentResolver.delete(CallLog.Calls.CONTENT_URI, 
						CallLog.Calls._ID+"=?", 
						new String[] {read_cv.getAsString(CallLog.Calls._ID)});				

		     				        		
		        		if (read_cv.getAsInteger(CallLog.Calls.TYPE)==CallLog.Calls.INCOMING_TYPE){
		        	   		String sipNumber =p.getString("sipnumber","0000000000");
			        			        			
		        			Cursor c1=contentResolver.query(CallLog.Calls.CONTENT_URI,
					    			null,
		        					CallLog.Calls.NUMBER+"=? AND "+CallLog.Calls.TYPE+"=? ",
					    			new String[] {sipNumber, String.valueOf(CallLog.Calls.MISSED_TYPE)},
		        					CallLog.Calls.DATE+" DESC");
		        			    
		        		        
		        		    ContentValues read_cv1 = null;
		        		    if (c1!=null) {
		        		        if (c1.moveToFirst()){
		        		        	read_cv1 = new ContentValues();
		        		        	DatabaseUtils.cursorRowToContentValues(c1, read_cv1);
		        		        	if  (read_cv1.getAsLong(CallLog.Calls.DATE)>(callStart-100000)) {
		        		        		contentResolver.delete(CallLog.Calls.CONTENT_URI, 
		        						CallLog.Calls._ID+"=?", 
		        						new String[] {read_cv1.getAsString(CallLog.Calls._ID)});
		        		        	}
		        		        }
		        		    }
		        	   		
		        			ContentValues cv = new ContentValues();	    		        
		        			cv.put(CallLog.Calls.NUMBER, sipNumber);    		       
		        			cv.put(CallLog.Calls.TYPE, CallLog.Calls.INCOMING_TYPE);
		        			cv.put(CallLog.Calls.NEW, 0);
		        			cv.put(CallLog.Calls.DURATION, read_cv.getAsString(CallLog.Calls.DURATION));
		        			cv.put(CallLog.Calls.DATE, read_cv.getAsString(CallLog.Calls.DATE));
		        			contentResolver.insert(CallLog.Calls.CONTENT_URI, cv);
		        		}
		        	}
		        }  
		    }  
			e.putBoolean("gsmTrigger",false);
			e.putBoolean("sipTrigger",false);
			e.putBoolean("waitPhoneIdle",false);
			e.putInt("counter", 1);


			e.commit();
		    
		}
/*		
			private void Logge(String sted){
			Log.setLogLevel(5);
			Integer counter=p.getInt("counter", 1);
			Log.v(THIS_FILE, counter+">"+sted+" sT:"+p.getBoolean("sipTrigger", false)+" gT:"+p.getBoolean("gsmTrigger", false)+" wI:"+p.getBoolean("waitPhoneIdle", false));
			e.putInt("counter", counter+1);
			
		}
*/
}
	

